package com.zdy.adapter;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.example.networklibrary.BaseObserver;
import com.example.networklibrary.MD5;
import com.example.networklibrary.RxHttp;
import com.example.networklibrary.SharedPreferencesUtils;
import com.example.networklibrary.ToastUtils;
import com.example.networklibrary.config.KeyInterface;
import com.example.networklibrary.entity.RequestEntity;
import com.example.networklibrary.model.QuestionsModel;
import com.example.networklibrary.model.ProductRecordModel;
import com.zdy.showgoods.ProductFragment;
import com.zdy.showgoods.R;
import com.zdy.utils.AppUtil;
import com.zdy.utils.GlideApp;
import com.zdy.utils.StringUtils;
import com.zdy.widget.MultiCheckDialogFragment;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class ProductRecordListAdapter extends BaseQuickAdapter<ProductRecordModel, BaseViewHolder> {
    private Context context;
    private int position = 0;
    private ProductRecordModel productRecordModel;
    private AppCompatActivity appCompatActivity;

    public ProductRecordListAdapter(AppCompatActivity context, List<ProductRecordModel> data) {
        super(R.layout.item_callback, data);
        appCompatActivity = context;
    }

    @Override
    protected void convert(BaseViewHolder helper, ProductRecordModel item) {
        position = helper.getAdapterPosition();
        context = helper.itemView.getContext();
        ImageView img = helper.itemView.findViewById(R.id.item_product_img);
        if (TextUtils.isEmpty(item.getImage_id())) {
            GlideApp.with(context).load(R.mipmap.img_test_2).into(img);
        } else {
            String imgURL = AppUtil.returnImgURL(context) + item.getImage_id();

            GlideApp.with(context).load(imgURL).error(R.mipmap.img_test_2).into(img);
        }
        helper.setText(R.id.item_product_name, "品名：" + StringUtils.returnString(item.getSku_name()));
        helper.setText(R.id.item_product_introduce, StringUtils.returnString(item.getSku_statement()));
        helper.setText(R.id.item_staff_name, "接待：" + StringUtils.returnString(item.getStaff_name()));
        helper.setText(R.id.item_guest_name, "顾客：" + StringUtils.returnString(item.getCustomer_name()));
        helper.setText(R.id.item_time, "时间：" + StringUtils.returnTime(item.getCreate_time()));
        helper.setText(R.id.item_callback_tv, 1 == item.getFeed_status() ? "已反馈" : "反馈");
        helper.setOnClickListener(R.id.item_callback_tv, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (1 == item.getFeed_status()) return;
                productRecordModel = item;
                loadQuestion(item.getHistory_id());
            }
        });
    }

    public void showMultiChoiceDialogFragment(List<QuestionsModel> questions, int histroyID) {
        MultiCheckDialogFragment multiChoiceDialogFragment = new MultiCheckDialogFragment();
        Bundle bundle = new Bundle();
        bundle.putString("List",JSONObject.toJSONString(questions));
        multiChoiceDialogFragment.setArguments(bundle);
        multiChoiceDialogFragment.setOnSelectedListener(new MultiCheckDialogFragment.OnSelectedListener() {
            @Override
            public void onSelected(String ids) {
                commitSelection(ids, histroyID);
                multiChoiceDialogFragment.dismiss();
            }
        });
        multiChoiceDialogFragment.show(appCompatActivity.getSupportFragmentManager(),"MultiCheckDialogFragment");
    }


    private void loadQuestion(int history_id) {
        RequestEntity requestEntity = new RequestEntity();
        JSONObject header = new JSONObject();
        header.put("request_seq", KeyInterface.REQUEST_SEQ);
        header.put("sign", "");
        header.put("sys_id", KeyInterface.SYS_ID);
        header.put("tra_code", KeyInterface.QUESTION);
        requestEntity.setHeader(header);

        try {
            String signString = JSONObject.toJSONString(requestEntity);
            String sign = MD5.getSign(signString);
            header.put("sign", sign);
            requestEntity.setHeader(header);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String json = "";
        try {
            json = URLEncoder.encode(JSONObject.toJSONString(requestEntity), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        RxHttp.getInstance()
                .getSyncServer()
                .parseArray(SharedPreferencesUtils.getString(appCompatActivity, KeyInterface.AppURL), json)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<JSONArray>() {
                    @Override
                    public void onSuccess(JSONArray result) {
                        try {

                            showMultiChoiceDialogFragment(JSONArray.parseArray(result.toJSONString(), QuestionsModel.class), history_id);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Throwable e, String errorMsg) {
                    }
                });
    }

    private void commitSelection(String ids, int historyId) {
        RequestEntity requestEntity = new RequestEntity();
        JSONObject body = new JSONObject();
        body.put("history_id", historyId + "");
        body.put("pick", ids);
        requestEntity.setBody(body);
        JSONObject header = new JSONObject();
        header.put("request_seq", KeyInterface.REQUEST_SEQ);
        header.put("sign", "");
        header.put("sys_id", KeyInterface.SYS_ID);
        header.put("tra_code", KeyInterface.COMMIT);
        requestEntity.setHeader(header);

        try {
            String signString = JSONObject.toJSONString(requestEntity);
            String sign = MD5.getSign(signString);
            header.put("sign", sign);
            requestEntity.setHeader(header);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String json = "";
        try {
            json = URLEncoder.encode(JSONObject.toJSONString(requestEntity), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        RxHttp.getInstance()
                .getSyncServer()
                .parseString(SharedPreferencesUtils.getString(appCompatActivity, KeyInterface.AppURL), json)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public void onSuccess(String result) {
                        try {
                            productRecordModel.setFeed_status(1);
                            notifyDataSetChanged();
                            ToastUtils.showShort("您的反馈已提交成功");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Throwable e, String errorMsg) {
                        ToastUtils.showShort(errorMsg);
                    }
                });
    }
}
